package com.my.valve.v1;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by ZhongGang
 * at 2018/9/4 17:25
 */
public class Valve {
    private long time;//时间
    private TimeUnit timeUnit;//时间单位
    private int capacity;//允许通过的最大流量
    private int times;//实际通过的流量，超过单位时间设置归零，开启下一轮验证

    private Date startTime;//阀门开启时间，超过单位时间设置，可修改
    private Date endTime;//阀门关闭时间，超过单位时间设置，可修改

    public void acquire() throws InterruptedException {
        this.acquire(1);
    }

    public void acquire(int acquires) throws InterruptedException {
        lazyInitialize();
        Date acquireTime = new Date();
        if (acquireTime.compareTo(this.startTime) >= 0 && acquireTime.compareTo(this.endTime) < 0) {
            if (this.times >= this.capacity) {
                TimeUnit.MILLISECONDS.sleep(this.endTime.getTime() - acquireTime.getTime());
                this.startTime = null;
                this.endTime = null;
                this.times = 0;
            }
            this.times += acquires;
        }

        throw new UnsupportedOperationException();
    }

    private void lazyInitialize() {
        if (this.startTime == null && this.endTime == null) {
            this.startTime = new Date();
            this.endTime = new Date(this.startTime.getTime() + this.timeUnit.toMillis(this.time));
        }
    }
}
